package com.carkeeper.subject.service.impl;

import com.aliyuncs.exceptions.ClientException;
import com.carkeeper.subject.dao.StoreMapper;
import com.carkeeper.subject.dao.StoreUserMapper;
import com.carkeeper.subject.pojo.Store;
import com.carkeeper.subject.pojo.StoreFull;
import com.carkeeper.subject.pojo.StoreUser;
import com.carkeeper.subject.service.StoreService;
import com.carkeeper.subject.service.StoreUserService;
import com.carkeeper.subject.utils.SMSUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import net.bytebuddy.implementation.bytecode.Throw;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;
import sun.security.provider.MD5;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Map;

@Service
public class StoreUserServiceImpl implements StoreUserService {

    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    private StoreUserMapper storeUserMapper;

    /**
     * 查询服务商
     * @param map 封装的查询条件
     * @return
     */
    @Override
    public Page<Store> findPage(Map map) {
        //设置分页
        setPageQuery(map);
        //获取查询条件
        Example example = getExample(map);
        List<Store> stores = storeMapper.selectByExample(example);
        //遍历所有服务商
        for (Store store : stores) {
            StoreUser storeUser = new StoreUser();
            storeUser.setStoreId(Long.toString(store.getId()));
            //通过服务商id去查询服务商用户
            List<StoreUser> storeUserList = storeUserMapper.select(storeUser);
            //有用户表示已经创建过管理员
            if (storeUserList.size()>0&&storeUserList!=null){
                store.setIsAdmin("1");
            }else {
                store.setIsAdmin("0");
            }
        }
        return (Page<Store>) stores;
    }
    /**
     * 根据服务商id带条件查询旗下用户
     * @param map 查询条件
     * @return
     */
    @Override
    public Page<StoreUser> findQueryByStoreId(Map map) {
        //设置分页
        setPageQuery(map);
        String storeId = (String) map.get("storeId");
        //根据storeid丶手机号丶用户名丶姓名查
        Example example =new Example(StoreUser.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("storeId",storeId);
        if (map.get("username")!=null){
        criteria.andEqualTo("username",map.get("username"));
        }
        if (map.get("phone")!=null){
            criteria.andEqualTo("phone",map.get("phone"));
        }
        if (map.get("realname")!=null){
            criteria.andEqualTo("realname",map.get("realname"));
        }
        List<StoreUser> storeUserList = storeUserMapper.selectByExample(example);

        return (Page<StoreUser>) storeUserList;
    }

    /**
     * 添加管理员
     * @param storeUser
     */
    @Override
    public void addUser(StoreUser storeUser,String storeId) {
        String username = storeUser.getUsername();
        //根据用户名查
        Example example =new Example(storeUser.getClass());
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username",username);
        StoreUser storeUser1 = storeUserMapper.selectOneByExample(example);

        if (storeUser1!=null){
            throw new RuntimeException("用户已存在");
        }

        //添加商户id
        storeUser.setStoreId(storeId);
        //设置为管理员
        storeUser.setIsAdmin("1");
        //默认状态为正常
        storeUser.setStatus("0");
        //保存加密前的密码
        String password = storeUser.getPassword();
        //加密
        String gensalt = BCrypt.gensalt();
        String BCpassword = BCrypt.hashpw(storeUser.getPassword(), gensalt);
        storeUser.setPassword(BCpassword);
        storeUserMapper.insertSelective(storeUser);
        //添加成功后给用户发送短信告知用户名密码
        try {
            //SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,storeUser.getPhone(),"用户名为:"+storeUser.getUsername()+";密码为:"+storeUser.getPassword());
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,storeUser.getPhone(),"用户名为:**"+";密码为:**");
            System.out.println("用户名:"+storeUser.getUsername()+";密码为:"+password);
        } catch (ClientException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void lockOrUnlock(String id) {
        //根据id查出服务商
        StoreUser storeUser = storeUserMapper.selectByPrimaryKey(id);
        if (storeUser!=null){
            String status = storeUser.getStatus();
            if ("0".equals(status)){
                //状态是未锁定
                storeUser.setStatus("1");//改为锁定状态
            }else {
                storeUser.setStatus("0");
            }
        }
        //更新数据
        storeUserMapper.updateByPrimaryKey(storeUser);
    }

    /**
     * 重置密码
     * @param id
     */
    @Override
    public void resetPassword(String id) {
        StoreUser storeUser = storeUserMapper.selectByPrimaryKey(id);
        if (storeUser!=null){
            //加密
            String gensalt = BCrypt.gensalt();
            String BCpassword = BCrypt.hashpw("123456", gensalt);
            storeUser.setPassword(BCpassword);
            try {
                //修改后给用户发送短信通知
                SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,storeUser.getPhone(),"123456");
            } catch (ClientException e) {
                e.printStackTrace();
            }
            storeUserMapper.updateByPrimaryKey(storeUser);
        }else {
            throw new RuntimeException("查无此人");
        }
    }

    /**
     * 拼接查询条件
     * @param map
     * @return
     */
    private Example getExample(Map map){
        //查询通过审核的服务商
        Example example=new Example(Store.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andBetween("status","1","3");
        //拼接查询条件
        if (map.get("code")!=null&&!"".equals(map.get("code"))){
            criteria.andEqualTo("code",map.get("code"));
        }
        if (map.get("simpleName")!=null&&!"".equals(map.get("simpleName"))){
            criteria.andEqualTo("simpleName",map.get("simpleName"));
        }
        if (map.get("status")!=null&&!"".equals(map.get("status"))){
            criteria.andEqualTo("status",map.get("status"));
        }
        if (map.get("type")!=null&&!"".equals(map.get("type"))){
            criteria.andEqualTo("type",map.get("type"));
        }
        if (map.get("province")!=null&&!"".equals(map.get("province"))){
            criteria.andEqualTo("province",map.get("province"));
        }
        if (map.get("city")!=null&&!"".equals(map.get("city"))){
            criteria.andEqualTo("city",map.get("city"));
        }
        return example;
    }

    /**
     * 设置分页
     * @param map
     */
    private void setPageQuery(Map map){
        //设置分页参数
        Integer page=1;
        Integer size=10;
        //设置默认值为1
        if (map.get("page")!=null&&!"".equals(map.get("page"))){
            page= Integer.parseInt((String)map.get("page")) ;
        }
        if (map.get("size")!=null&&!"".equals(map.get("size"))){
            size= Integer.parseInt((String)map.get("size")) ;
        }
        //设置分页
        PageHelper.startPage(page,size);
    }
}
